package com.yinp.proapp.module.customview.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import com.yinp.proapp.R;
import com.yinp.proapp.utils.AppUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * 一个加减的控件，可以输入，也可以直接加减
 */
public class AddSubtractView extends LinearLayout {
    public AddSubtractView(Context context) {
        super(context);
        init(null);
    }

    public AddSubtractView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public AddSubtractView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public AddSubtractView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    private static final String DIGITS = "0123456789";
    private int radius;//圆角
    private TextView subtract;//减
    private EditText value;//值
    private TextView add;//加
    RectF rectF = new RectF();
    Paint linePaint;
    int strokeColor;//边框的颜色
    int strokeWidth;//边框粗细
    int addLeftRightPd, subtractLeftRightPd, valueLeftRightPd, topBottomPad;//边距
    int maxEms;//最多8个数字
    int addTextSize, valueTextSize, subtractTextSize;
    int addTextColor, valueTextColor, subtractTextColor;
    int defaultValue = 0;//默认显示的数值
    boolean isClickAdd, isClickSubtract;


    private void init(AttributeSet attrs) {
        isFirst = true;
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.AddSubtractView);
        radius = ta.getInteger(R.styleable.AddSubtractView_mRadius, 0);
        strokeColor = ta.getColor(R.styleable.AddSubtractView_mStrokeColor, ContextCompat.getColor(getContext(), R.color.gray_e5e5e5));
        strokeWidth = ta.getInteger(R.styleable.AddSubtractView_mStrokeWidth, 1);//dp
        addLeftRightPd = ta.getInteger(R.styleable.AddSubtractView_addLeftRightPd, 4);
        subtractLeftRightPd = ta.getInteger(R.styleable.AddSubtractView_subtractLeftRightPd, 4);
        valueLeftRightPd = ta.getInteger(R.styleable.AddSubtractView_valueLeftRightPd, 8);
        topBottomPad = ta.getInteger(R.styleable.AddSubtractView_topBottomPad, 4);
        maxEms = ta.getInteger(R.styleable.AddSubtractView_maxEms, 8);
        addTextSize = ta.getInteger(R.styleable.AddSubtractView_addTextSize, 12);
        valueTextSize = ta.getInteger(R.styleable.AddSubtractView_valueTextSize, 14);
        subtractTextSize = ta.getInteger(R.styleable.AddSubtractView_subtractTextSize, 12);
        addTextColor = ta.getColor(R.styleable.AddSubtractView_addTextColor, ContextCompat.getColor(getContext(), R.color.gray_e5e5e5));
        valueTextColor = ta.getColor(R.styleable.AddSubtractView_valueTextColor, ContextCompat.getColor(getContext(), R.color.gray_e5e5e5));
        subtractTextColor = ta.getColor(R.styleable.AddSubtractView_subtractTextColor, ContextCompat.getColor(getContext(), R.color.gray_e5e5e5));
        defaultValue = ta.getInteger(R.styleable.AddSubtractView_defaultValue, 0);


        ta.recycle();
        if (maxEms > 8) {
            maxEms = 8;
        }
        //初始化画笔，抗锯齿和防抖动
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        linePaint.setColor(strokeColor);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeWidth(AppUtils.dpToPx(strokeWidth));

        radius = AppUtils.dpToPx(radius);
        addLeftRightPd = AppUtils.dpToPx(addLeftRightPd);
        subtractLeftRightPd = AppUtils.dpToPx(subtractLeftRightPd);
        valueLeftRightPd = AppUtils.dpToPx(valueLeftRightPd);
        topBottomPad = AppUtils.dpToPx(topBottomPad);

        subtract = new TextView(getContext());
        subtract.setTextSize(addTextSize);
        subtract.setText("−");
        subtract.setTextColor(subtractTextColor);
        subtract.setPadding(subtractLeftRightPd, topBottomPad, subtractLeftRightPd, topBottomPad);

        value = new EditText(getContext());
        value.setTextSize(valueTextSize);
        value.setText(String.valueOf(defaultValue));
        value.setBackground(null);
        value.setMaxEms(maxEms);
        value.setTextColor(valueTextColor);
        value.setInputType(InputType.TYPE_CLASS_PHONE);
        value.setPadding(valueLeftRightPd, topBottomPad, valueLeftRightPd, topBottomPad);
        value.setKeyListener(DigitsKeyListener.getInstance(DIGITS));//保证只能是数字
        value.setTypeface(null, Typeface.BOLD);//加粗
        value.setSelection(1);

        add = new TextView(getContext());
        add.setTextSize(subtractTextSize);
        add.setText("+");
        add.setTextColor(addTextColor);
        add.setPadding(addLeftRightPd, topBottomPad, addLeftRightPd, topBottomPad);


        addView(subtract);

        addView(value);

        addView(add);

        initEvent();
        setWillNotDraw(false);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        subtract.setOnClickListener(v -> {
            int data = Integer.parseInt(value.getText().toString());
            if (data == 0) {
                return;
            } else {
                value.setText(String.valueOf(--data));
            }
        });
        add.setOnClickListener(v -> {
            int data = Integer.parseInt(value.getText().toString());
            value.setText(String.valueOf(++data));
        });
        subtract.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_MOVE:
                    isClickSubtract = true;
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    isClickSubtract = false;
                    break;
            }
            return false;
        });
        add.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_MOVE:
                    isClickAdd = true;
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    isClickAdd = false;
                    break;
            }
            return false;
        });
        subtract.setOnLongClickListener(v -> {
            Observable<Long> observable = Observable.interval(0, 100, TimeUnit.MILLISECONDS);
            observable.takeUntil(aLong -> {
                if (isClickSubtract) {
                    return false;
                } else {
                    return true;
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Long>() {
                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }

                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Long aLong) {
                            int data = Integer.parseInt(value.getText().toString());
                            if (data != 0) {
                                value.setText(String.valueOf(--data));
                            }
                        }
                    });
            return true;
        });
        add.setOnLongClickListener(v -> {
            Observable<Long> observable = Observable.interval(0, 100, TimeUnit.MILLISECONDS);
            observable.takeUntil(aLong -> !isClickAdd).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Long>() {
                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }

                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Long aLong) {
                            int data = Integer.parseInt(value.getText().toString());
                            value.setText(String.valueOf(++data));
                        }
                    });
            return true;
        });
        value.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (is) {
                    is = false;
                    return;
                }
                if (TextUtils.isEmpty(s)) {
                    value.setText("0");
                    value.setSelection(1);
                }
                if (s.toString().startsWith("0") && s.length() > 1) {
                    value.setText(s.toString().substring(1, s.length()));
                    value.setSelection(s.length() - 1);
                }
                if (s.length() > maxEms) {
                    value.setText(s.toString().substring(0, s.length() - 1));
                    value.setSelection(s.length() - 1);
                }
                if (onValueChangedListener != null) {
                    onValueChangedListener.onValueChanged(Integer.parseInt(value.getText().toString()));
                }
            }
        });
    }

    /**
     * 修改默认值
     *
     * @param defaultValue
     */
    public void setDefaultValue(int defaultValue) {
        is = true;
        value.setText(String.valueOf(defaultValue));
    }

    private boolean is = false;

    @Override
    public boolean canScrollHorizontally(int direction) {
        return true;
    }

    @Override
    public boolean canScrollVertically(int direction) {
        return false;
    }

    boolean isFirst = false;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isFirst) {
            rectF.left = 0;
            rectF.top = 0;
            rectF.right = getWidth();
            rectF.bottom = getHeight();
        }
        canvas.drawLine(subtract.getRight(), 0, subtract.getRight(), getHeight(), linePaint);
        canvas.drawLine(add.getLeft(), 0, add.getLeft(), getHeight(), linePaint);
        canvas.drawRoundRect(rectF, 20, 20, linePaint);
    }

    /**
     * 传递改变的数值
     */
    public interface OnValueChangedListener {
        void onValueChanged(int value);
    }

    private OnValueChangedListener onValueChangedListener;

    public void setOnValueChangedListener(OnValueChangedListener onValueChangedListener) {
        this.onValueChangedListener = onValueChangedListener;
    }
}
